package com.jn.glide.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.glide.R;
import com.jn.glide.entity.AvatarEntity;

import java.util.List;

public class AvatarListAdapter extends RecyclerView.Adapter<AvatarListAdapter.ViewHolder> {
    private List<AvatarEntity.ResultDTO.ListDTO> mList;
    private OnItemClickListener mListener;

    public AvatarListAdapter(List<AvatarEntity.ResultDTO.ListDTO> list) {
        mList = list;
    }

    public void updateData(List<AvatarEntity.ResultDTO.ListDTO> list) {
        mList.clear();
        mList = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public AvatarListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AvatarListAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        AvatarEntity.ResultDTO.ListDTO listDTO = mList.get(position);
        holder.textView1.setText(listDTO.getName());
        holder.layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onItemClick(listDTO.getIcon());
                }
            }
        });
        Glide.with(holder.imageView)
                .load(listDTO.getIcon())
                .into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout layout;
        ImageView imageView;
        TextView textView1;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            layout = itemView.findViewById(R.id.recycler_item);
            imageView = itemView.findViewById(R.id.image);
            textView1 = itemView.findViewById(R.id.name);
        }
    }

    public void addItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(String url);
    }
}
